<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--资产树数据-->
      <el-col :span="5" :xs="24" class="padding-content possession-tree">
<!--        <div class="head-container">-->
<!--          <el-input-->
<!--            v-model="possessionTreeSearch"-->
<!--            placeholder="请输入资产树名称"-->
<!--            clearable-->
<!--            size="small"-->
<!--            prefix-icon="el-icon-search"-->
<!--            style="margin-bottom: 20px"-->
<!--          />-->
<!--        </div>-->
        <div class="head-container">
          <h4 class="h4">
            <span class="fill-parent">资产树</span>
            <span class="pull-right pointer"@click="handleCommand('handleAdd')">
              <i class="el-icon-plus"></i>
            </span>
          </h4>
        </div>
        <div class="head-container">
          <el-tree
            :data="possessionTree.possessionTreeOptions"
            :props="possessionTree.defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            class="possession-tree"
            node-key="id"
          >
<!--            @node-click="handleNodeClick"-->
<!--          >-->
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <span :title="data.description" @click="handleNodeClick(data)">{{ node.label }}</span>
              <span style="float: right;">
                <el-dropdown size="mini" @command="(command) => handleCommand(command, data)" >
                    <span class="el-dropdown-link" >
                      <i class="el-icon-more"></i>
                    </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="handleAdd" icon="el-icon-plus"
                    >新增</el-dropdown-item>
                    <el-dropdown-item command="handleRefactor" icon="el-icon-edit"
                    >修改</el-dropdown-item>
                    <el-dropdown-item command="handleDelete" icon="el-icon-delete"
                    >删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </span>
            </span>
          </el-tree>
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="19" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="3">
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleObjectAssociate"
            >关联数据对象</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleFileAssociate"
            >关联文件</el-button>
          </el-col>
<!--          <el-col :span="6">-->
<!--            <div class="head-container">-->
<!--              <el-input-->
<!--                v-model="possessionName"-->
<!--                placeholder="请输入数据资产名称"-->
<!--                clearable-->
<!--                size="small"-->
<!--                prefix-icon="el-icon-search"-->
<!--                style="margin-bottom: 20px"-->
<!--              />-->
<!--            </div>-->
<!--          </el-col>-->
        </el-row>

        <el-table v-loading="loading" :data="possessionList.list">
          <el-table-column label="数据资产编号" align="center" key="relationId" prop="relationId" v-if="columns[0].visible" />
          <el-table-column label="数据资产名称" align="center" key="name" prop="name" v-if="columns[1].visible" :show-overflow-tooltip="true" />
          <el-table-column label="标识码/文件路径" align="center" key="code" prop="code" v-if="columns[2].visible" :show-overflow-tooltip="true" />
          <el-table-column label="数据资产类型" align="center" key="type" prop="type" v-if="columns[3].visible" :show-overflow-tooltip="true" />
          <el-table-column label="数据源" align="center" key="data_source" prop="data_source" v-if="columns[4].visible" width="120" />
          <el-table-column label="创建时间" align="center" prop="create_time" v-if="columns[5].visible" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="160"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleCancelAssociate(scope.row)"
              >取消关联</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="possessionList.total>0"
          :total="possessionList.total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="pagingPossessionList"
        />
      </el-col>
    </el-row>

    <!-- 关联配置对话框 -->
    <el-dialog :title="associate.title" :visible.sync="associate.openAssociateDialog" width="700px" append-to-body>
      <el-row>
                  <el-col :span="8">
                    <div class="head-container">
                      <el-input
                        v-model="associate_search_name_or_code"
                        placeholder="请输入搜索关键字"
                        clearable
                        size="small"
                        prefix-icon="el-icon-search"
                        style="margin-bottom: 20px"
                      />
                    </div>
                  </el-col>
      </el-row>
      <el-table v-loading="loading" :data="associate.pagedList" >
<!--        @selection-change="handleSelectionChange">-->
<!--        <el-table-column type="selection" width="50" align="center" />-->
        <el-table-column label="编号" align="id" key="id" prop="id" v-if="columns[2].visible" :show-overflow-tooltip="true" />
        <el-table-column label="名称" align="name" key="name" prop="name" v-if="columns[3].visible" :show-overflow-tooltip="true" />
        <el-table-column label="文件大小" align="size" key="size" prop="size" v-if="associate.isFileList" width="120" />
        <el-table-column label="文件路径" key="path" prop="path" v-if="associate.isFileList" width="120" />
        <el-table-column label="创建时间" key="createTime" prop="createTime" v-if="associate.isFileList" width="120" />
        <el-table-column label="路径" key="dataPath" prop="dataPath" v-if="!associate.isFileList" width="120" />
        <el-table-column label="创建时间" key="reviseTime" prop="reviseTime" v-if="!associate.isFileList" width="120" />
        <el-table-column
          label="操作"
          align="center"
          width="100"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row.associated"
              size="mini"
              type="text"
              icon="el-icon-check"
              disabled
            >已关联</el-button>
            <el-button v-else
                       size="mini"
                       type="text"
                       icon="el-icon-check"
                       @click="handleAddAssociate(scope.row)"
            >关联</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="associate.pagingParams.total>0"
        :total="associate.pagingParams.total"
        :page.sync="associate.pagingParams.pageNum"
        :limit.sync="associate.pagingParams.pageSize"
        @pagination="pagingObjectList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAssociate">确 定</el-button>
        <el-button @click="associate.openAssociateDialog=false;">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改资产树配置对话框 -->
    <el-dialog :title="treeNodeForm.dialogTitle" :visible.sync="treeNodeForm.openDialog" width="600px" append-to-body>
      <el-form ref="treeNodeForm" :model="treeNodeForm.form" :rules="treeNodeForm.rules" label-width="80px">
        <el-row>
            <el-form-item label="名称" prop="nodeName">
              <el-input v-model="treeNodeForm.form.name" placeholder="请输入资产树名称" maxlength="30" />
            </el-form-item>
        </el-row>
        <el-row>
            <el-form-item label="说明" prop="note">
              <el-input v-model="treeNodeForm.form.description" placeholder="请输入说明文本" maxlength="200" />
            </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitTreeNodeForm">确 定</el-button>
        <el-button @click="treeNodeForm.openDialog=false;">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {associate as addAssociate,treeselect,listPossession,addNode,updateNode,delNode,unassociatePossession} from "@/api/manage/possession";
import {listDataObject} from "@/api/manage/dataObject";
import {listFiles} from "@/api/manage/file";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Possession",
  dicts: [],
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      //
      possessionTreeSearch:"",
      possessionTree:{
        treeList:[],
        possessionTreeNodeName:null,
        possessionTreeOptions:[],
        possessionTreeProps:[],
        defaultProps: {
          children: "children",
          label: "name"
        },
      },
      possessionList: {
        originList:[],
        list:[],
        total:0,
        associateNodeId:undefined,
      },
      associate:{
        openAssociateDialog: false,
        title:"",
        nodeId:-1,
        ids:[],
        isFileList:false,
        originList:[],
        list:[],
        pagedList:[],
        pagingParams:{
          pageNum: 1,
          pageSize: 10,
          total:undefined,
        }
      },
      associate_search_name_or_code:"",
      // 默认密码
      initPassword: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetsId:undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      treeNodeForm:{
        openDialog:false,
        dialogTitle:"",
        form:{
          parentId:0,
          name:"",
          description:"",
        },
        rules:{
          name:[
            { required: true, message: "名称不能为空", trigger: "blur" },
            { min: 1, max: 20, message: '名称长度必须介于 1 和 20 之间', trigger: 'blur' }
          ],
          description:[
            { required: true, message: "不能为空", trigger: "blur" },
            { max: 200, message: '长度必须小于 200', trigger: 'blur' }
          ],
        }
      },
    };
  },
  watch: {
    // 根据名称筛选树
    possessionTreeSearch(val){
      this.$refs.tree.filter(val);
    },
    associate_search_name_or_code(val){
      let newList=[];
      this.associate.originList.forEach(item=>{
        if(item.coopName.search(val)!==-1||item.account.search(val)!==-1){
          newList.push(item);
        }
      });
      this.associate.list=newList;
      this.resetListPage();
    }
  },
  created() {
    // this.getList();
    // this.getConfigKey("sys.user.initPassword").then(response => {
    //   this.initPassword = response.msg;
    // });
    this.getTree();
  },
  methods: {
    /** 查询资产列表 */
    getPossessionList() {
      this.loading = true;
      listPossession(this.addDateRange(this.queryParams)).then(response => {
          this.possessionList.originList = response.data;
          this.possessionList.total = response.data.length;
          this.possessionList.associateNodeId=this.queryParams.assetsId;
          this.queryParams.pageNum=1;
          this.queryParams.pageSize=10;
          // this.queryParams.assetsId=undefined;
          this.pagingPossessionList();
          this.loading = false;
        }
      );
    },
    pagingPossessionList(){
      let params=this.queryParams;
      this.possessionList.list=this.possessionList.originList.slice(
        (params.pageNum-1)*params.pageSize,
        params.pageNum*params.pageSize
      );
    },
    /** 查询下拉树结构 */
    getTree() {
      treeselect().then(response => {
        this.possessionTree.possessionTreeOptions = this.handleTree(response.data,"assetsId");
        this.queryParams.assetsId=this.possessionTree.possessionTreeOptions[0]?.assetsId;
        this.getPossessionList();
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.assetsId = data.assetsId;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getPossessionList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleAdd":
          this.handleNodeAdd(row);
          break;
        case "handleRefactor":
          this.handleNodeRefactor(row);
          break;
        case "handleDelete":
          this.handleNodeDelete(row);
          break;
        default:
          break;
      }
    },
    pagingObjectList(){
      let params=this.associate.pagingParams;
      this.associate.pagedList=this.associate.list.slice(
        (params.pageNum-1)*params.pageSize,
        params.pageNum*params.pageSize
      );
    },
    resetListPage(){
      this.associate.pagingParams.pageNum=1;
      this.associate.pagingParams.pageSize=10;
      this.associate.pagingParams.total=this.associate.list.length;
      this.pagingObjectList();
    },
    handleNodeAdd(row){
      this.treeNodeForm.form.name="";
      this.treeNodeForm.form.description="";
      if(row){
        this.treeNodeForm.form.parentId=row.assetsId;
      }else {
        this.treeNodeForm.form.parentId=0;
      }
      this.treeNodeForm.form.assetsId=undefined;
      this.treeNodeForm.dialogTitle="添加资产树节点";
      this.treeNodeForm.openDialog=true;
    },
    handleNodeRefactor(row){
      this.treeNodeForm.form.assetsId=row.assetsId;
      this.treeNodeForm.form.name=row.name;
      this.treeNodeForm.form.description=row.description;
      this.treeNodeForm.form.parentId=undefined;
      this.treeNodeForm.dialogTitle="修改资产树节点";
      this.treeNodeForm.openDialog=true;
    },
    handleNodeDelete(row){
      const id = row.assetsId;
      this.$modal.confirm('是否确认名称为"' + row.name + '"的节点？').then(function() {
        return delNode(id);
      }).then(() => {
        this.getTree();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleCancelAssociate(row){
      const id = row.relationId;
      let name = row.name;
      const nodeId=this.possessionList.associateNodeId;
      this.$modal.confirm('是否确定去除"' + name + '"和"'+row.name+'"的关联？').then(function() {
        return unassociatePossession(nodeId,id);
      }).then(() => {
        this.getPossessionList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitTreeNodeForm:function(){
      this.$refs["treeNodeForm"].validate(valid=>{
        if(valid){
          let thenable;
          if(this.treeNodeForm.form.parentId!=undefined){
            thenable=addNode(this.treeNodeForm.form);
          }else{
            thenable=updateNode(this.treeNodeForm.form);
          }
          thenable.then(response=>{
            this.$modal.msgSuccess("成功");
            this.treeNodeForm.openDialog = false;
            this.getTree();
          });
        }
      });
    },
    // listFormat(originList){
    //
    // },
    markAssociatedOrNot(){
      let originList=this.associate.originList;
      let associatedIds=this.possessionList.originList.map(item=>(item.type+"-"+item.objectOrFile));
      let markedList=originList.map(item=>{
        let newItem=Object.assign({},item);
        let type=this.associate.isFileList?1:2;
        let id=type+"-"+item.id;
        newItem.associated=false;
        associatedIds.forEach(item=>{
          if(item==id){
            newItem.associated=true;
          }
        });
        return newItem;
      });
      this.associate.originList=markedList;
      this.associate.list=markedList;
    },
    handleFileAssociate(){
      this.associate_search_name_or_code=""
      this.associate.ids=[]
      this.associate.nodeId=this.possessionList.associateNodeId;
      this.associate.title="关联文件";
      this.associate.isFileList=true;
      this.associate.openAssociateDialog=true;
      this.loading=true;
      this.associate.originList=[];
      this.associate.list=[];
      this.associate.pagedList=[];
      listFiles().then(response =>{
        this.associate.originList=response.data;
        this.markAssociatedOrNot();
        this.resetListPage();
        this.loading=false;
      });
    },
    handleObjectAssociate(){
      this.associate_search_name_or_code=""
      this.associate.ids=[]
      this.associate.nodeId=this.possessionList.associateNodeId;
      this.associate.title="关联数据对象";
      this.associate.isFileList=false;
      this.associate.openAssociateDialog=true;
      this.loading=true;
      this.associate.originList=[];
      this.associate.list=[];
      this.associate.pagedList=[];
      listDataObject({}).then(response =>{
        this.associate.originList=response.data;
        this.markAssociatedOrNot();
        this.resetListPage();
        this.loading=false;
      });
    },
    handleSelectionChange(selection){
      this.associate.ids=selection.map(item=>item.id)
    },
    handleAddAssociate(row){
      let data;
      if(this.associate.isFileList){
        data={
          assetsId:this.associate.nodeId,
          name:row.name,
          code:row.path,
          type:1,
          objectOrFile:row.id,
        };
      }else{
        data={
          assetsId:this.associate.nodeId,
          name:row.name,
          code:row.dataPath,
          type:2,
          objectOrFile:row.id,
        };
      }
      addAssociate(data).then(response=>{
        this.$modal.msgSuccess("关联成功");
        this.getPossessionList();
        this.associate.openAssociateDialog=false;
      });
    },
    submitAssociate(){
      if(this.associate.ids.length===0){
        this.associate.openAssociateDialog=false;
        return;
      }
      addAssociate(this.associate.nodeId,this.associate.ids).then(response=>{
        this.$modal.msgSuccess("关联成功");
        this.associate.openAssociateDialog=false;
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
  .el-tree-node__content {
    padding-right: 0px;
  }
  .custom-tree-node{
    width: 100%;
  }
  .fill-parent{
    width: 100%;
  }
  .possession-tree{
    background: rgb(220,230,255);
    height: 100%;
  }
  .custom-tree-node:hover{

  }
  .app-container{
    height: 100%;
  }
</style>
